<template>
  <div class="table">
    <div class="crumbs">
      <i class="el-icon-info"></i> 歌曲管理
    </div>
    <div class="container">
      <div class="handle-box">
        <el-input placeholder="请输入歌曲名" v-model="selectSong" clearable class="handle-input"></el-input>
        <!--        添加歌曲按钮-->
        <el-button type="primary"  @click="AdddialogVisible = true">添加歌曲</el-button>
        <el-button type="danger"  @click="deleteSongAll">批量删除</el-button>
      </div>
    </div>
    <!--    歌曲信息表单区域-->
    <el-table :data="SongTableDate" style="width: 100% " border height="600px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="歌曲图片" width="110" align="center">
        <template slot-scope="scope">
          <div class="song-img">
            <img :src="getImgUrl(scope.row.pic)"  style="width: 100%"  />
          </div>
          <div class="play" @click="setSongUrl(scope.row.url,scope.row.name)">
            <div v-if="toggle ==scope.row.name">
              <svg class="icon">
                <use xlink:href="#icon-zanting"></use>
              </svg>
            </div>
            <div  v-if="toggle !==scope.row.name">
              <svg class="icon">
                <use xlink:href="#icon-bofanganniu"></use>
              </svg>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="歌手-歌名" width="120" align="center"></el-table-column>
      <el-table-column prop="introduction" label="专辑" width="150" align="center"></el-table-column>
      <el-table-column label="歌词"  align="center">
        <template slot-scope="scope">
          <ul style="height: 100px;overflow: scroll">
            <li v-for="(item,index) in parseLyric(scope.row.lyric)" :key="index">
              {{item}}
            </li>
          </ul>
        </template>
      </el-table-column>
      <el-table-column label="资源更新" width="150" align="center">
        <template slot-scope="scope">
<!--        更新图片-->
          <el-upload :action="uploadPicUrl(scope.row.id)" :before-upload="beforeSongAvatorUpload" :on-success="handleSongAvatorSuccess" >
            <el-button type="primary" size="mini" >更新图片</el-button>
          </el-upload>
          <br/>
<!--          更新歌曲-->
          <el-upload :action="updateSongUrl(scope.row.id)" :before-upload="updatebeforeSongAvatorUpload" :on-success="updatehandleSongAvatorSuccess" >
            <el-button  type="primary" size="mini" >更新歌曲</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="handleEdit(scope.row)" >编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--    分页功能区域-->
    <div class="PageNation">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-sizes="[5, 10, 20, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                     :total="SongTableDate.length">
      </el-pagination>
    </div>

    <!--    添加歌曲对话框-->
    <el-dialog title="添加歌曲" :visible.sync="AdddialogVisible" width="420px" center  >
      <!--      表单内容区域-->
      <el-form :model="AddSongfRuleForm" ref="ruleForm" label-width="100px" action="" id="tf">
         <div>
           <label>歌名</label>
           <el-input type="text" name="name"></el-input>
         </div>
        <div>
          <label>专辑</label>
          <el-input type="text" name="introduction"></el-input>
        </div>
        <div>
          <label>歌词</label>
          <el-input type="textarea" name="lyric"></el-input>
        </div>
        <div>
          <label>歌曲上传</label>
          <input type="file" name="file" >
        </div>
      </el-form>
      <!--      按钮区域-->
      <span slot="footer">
        <el-button @click="AdddialogVisible = false" >取 消</el-button>
        <el-button type="primary" @click="addSong" >确 定</el-button>
      </span>
    </el-dialog>

    <!--    修改歌曲对话框-->
    <el-dialog title="修改歌曲信息" :visible.sync="EditdialogVisible" width="420px" center >
      <!--      表单内容区域-->
      <el-form :model="EditSongRuleForm" :rules="EditingerRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="歌手-歌名" prop="name">
          <el-input v-model="EditSongRuleForm.name"  placeholder="歌手-歌名"></el-input>
        </el-form-item>
        <el-form-item label="专辑" prop="introduction">
          <el-input v-model="EditSongRuleForm.introduction"  placeholder="专辑"></el-input>
        </el-form-item>
        <el-form-item label="歌词" prop="lyric">
          <el-input v-model="EditSongRuleForm.lyric"  placeholder="歌词" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <!--      按钮区域-->
      <span slot="footer">
        <el-button @click="EditdialogVisible = false" >取 消</el-button>
        <el-button type="primary" @click="editSong" >确 定</el-button>
      </span>
    </el-dialog>

    <!--    删除对话框-->
    <el-dialog title="提示" :visible.sync="DeleteVisible" width="30%" >
      <div align="center">
        <span>是否确定删除</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="DeleteVisible = false">取 消</el-button>
        <el-button size="mini" type="danger" @click="DelteSongRow">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {delteSong, SongofSingerId, updateSong} from "../api";
import {mixin} from "../mixinx";
import {mapGetters} from 'vuex'
import '@/assets/js/iconfont.js'

export default {
  name: "SongSong",
  mixins: [mixin],
  data() {
    return {
      singer_id:'',
      singerName:'',
      AdddialogVisible: false,
      EditdialogVisible:false,
      DeleteVisible:false ,
      AddSongfRuleForm:{      //添加框
        name: '',
        singerName: '',
        introduction: '',
        lyric: ''
      },
      EditSongRuleForm:{
        id:'',
        name:'',
        introduction:'',
        lyric:'',
      },
      AddSongRules: {
        name: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
      },
      EditingerRules: {
        name: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ],
      },
      SongTableDate:[],
      tempDate:[],
      selectSong:'',
      pageSize:5,         //当前分页大小
      currentPage:1,      //当前页面
      idx:-1,       //当前选择项id
      multipleSelection:[],  //表格的多选项
      toggle:false ,   //播放器的显示图标状态
    }
  },
  watch:{
    // 监听搜索歌曲信息框，随输入文字变化
    selectSong: function(){
      if(this.selectSong == ''){
        this.SongTableDate = this.tempDate;
      }else{
        this.SongTableDate = [];
        for(let item of this.tempDate){
          if(item.name.includes(this.selectSong)){
            this.SongTableDate.push(item);
          }
        }
      }
    }
  },
  computed:{
    // 计算当前歌曲表里的所有歌曲数据
    allSongTableDate(){
      return this.SongTableDate.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize)
    },
    ...mapGetters([
      'id',
      'url',
      'isPlay'
    ])
  },
  created() {
    this.singer_id=this.$route.query.id
    this.singerName=this.$route.query.name
    this.getSongDate()
  },
  // 离开页面的方法
  // 离开播放页面，暂停歌曲
  destroyed(){
    this.$store.commit('setIsPlay',false)
  },
  methods: {
    // 查询所有歌曲
    getSongDate(){
      this.tempDate=[]
      this.SongTableDate=[]
      SongofSingerId(this.singer_id).then(res=>{
        this.tempDate=res
        this.SongTableDate=res
        this.currentPage=1
      })
    },
    // 添加歌曲事件
    addSong(){
      let _this = this;
      let form = new FormData(document.getElementById('tf'));
      form.append('singer_id',this.singer_id);
      form.set('name',this.singerName+'-'+form.get('name'));
      if(!form.get('lyric')){
        form.set('lyric','[00:00:00]暂无歌词');
      }
      let req = new XMLHttpRequest();
      req.onreadystatechange = function(){
        //req.readyState == 4 获取到返回的完整数据
        //req.status == 200 和后台正常交互完成
        if(req.readyState == 4 && req.status == 200){
          let res = JSON.parse(req.response);
          if(res.code){
            console.log(res)
            console.log(res.code)
            _this.getSongDate();
            _this.AddSongfRuleForm= {};
            _this.notify(res.msg,'success');
          }else{
            _this.notify('保存失败','error');
          }
        }
      }
      req.open('post',`${_this.$store.state.HOST}/song/add`,true);
      req.send(form);
      _this.AdddialogVisible = false;
    },
    // 把当前要修改的歌曲信息id传入修改对话框
    handleEdit(row){
      this.EditdialogVisible=true
      this.EditSongRuleForm={
        id:row.id,
        name:row.name,
        introduction:row.introduction,
        lyric:row.lyric,
      }
    },
    // 修改歌曲信息
    editSong(){
      let params=new URLSearchParams()
      params.append('id',this.EditSongRuleForm.id)
      params.append('name',this.EditSongRuleForm.name)
      params.append('introduction',this.EditSongRuleForm.introduction)
      params.append('lyric',this.EditSongRuleForm.lyric)
      updateSong(params).then(res =>{
        console.log(res)
        if(res.code==1){
          this.getSongDate()
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          });
        }else {
          this.$message({
            showClose: true,
            message: '修改失败',
            type: 'error'
          });
        }
      }).catch(err =>{
        console.log(err)
      })
      this.EditdialogVisible=false
     },
     // 确定删除歌曲
     DelteSongRow(){
       delteSong(this.idx).then(res =>{
        if(res){
          this.getSongDate()
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
        }else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'error'
          });
        }
      })
      this.DeleteVisible=false
    },
    // 解析歌词
    parseLyric(text){
      let lines=text.split("\n")
      let pattern=/\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g
      let result=[]
      for(let item of lines){
        let value=item.replace(pattern,'')
        result.push(value)
      }
      return result
    },
    // 更新图片
    uploadPicUrl(id){
       return `${this.$store.state.HOST}/song/updateSongPic?id=${id}`
     },
    // 歌曲上传图片之前的校验
    updatebeforeSongAvatorUpload(file) {
      var updateMsg=file.name.substring(file.name.lastIndexOf('.')+1)
      if(updateMsg!='mp3'){
        this.$message.error('上传文件只能是mp3格式')
        return false
      }
      return true;
    },
    // 歌曲上传图片成功后
    updatehandleSongAvatorSuccess(res) {
      let _this = this;
      if (res.code == 1) {
        _this.getSongDate();
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    // 切换歌曲播放
    setSongUrl(url,name){
      this.toggle=name
      this.$store.commit('setUrl',this.$store.state.HOST+url)
      if(this.isPlay){
        this.$store.commit('setIsPlay',false)
      }else{
        this.$store.commit('setIsPlay',true)
      }
    },
    // 更新图片
    updateSongUrl(id){
      return `${this.$store.state.HOST}/song/updateSongUrl?id=${id}`
    },
     // 获取当前页
    handleCurrentChange(val){
      this.currentPage=val
    },
    // 当前页的显示大小
    handleSizeChange(val){
       this.pageSize=val
     },

  }
}
</script>

<style scoped>
.handle-box{
   margin-bottom: 20px;
 }
.song-img{
  width: 100%;
  height: 80px;
  border-radius: 5px;
  margin-bottom: 5px;
  overflow: hidden;
}
.handle-input{
  width: 300px;
  display: inline-block;
}
.PageNation{
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
.play{
  position: absolute;
  z-index: 100;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  top: 18px;
  left: 15px;
}
.icon{
  width: 2em;
  height: 2em;
  color: deepskyblue;
  fill: currentColor;
  overflow: hidden;
}
</style>



























